package cn.virens.web.controller.admin.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import cn.virens.database.mysql.model.sys.SysRole;
import cn.virens.database.service.sys.SysRoleService;
import cn.virens.util.RequestUtil;
import cn.virens.util.shiro.Permission;
import cn.virens.util.ztree.Node;
import cn.virens.web.common.BaseDataTableController;

/**
 * 角色管理
 * 
 * @作者 : loioi
 * @创建时间 :2017年8月4日 上午11:04:21
 */
@Controller
@RequestMapping("/admin/system/role")
public class SysRoleContorller extends BaseDataTableController<SysRole, SysRoleService> {

	@Autowired
	public SysRoleContorller(SysRoleService service) {
		super("admin/system/role/", "system:role", service);
		this.setSaveUse(false, false, true);
	}

	@ResponseBody
	@RequestMapping("permissions.json")
	public Model getRolePermissions(HttpServletRequest request, Model model) {
		Integer roleID = RequestUtil.getValueInt(request, "id", 0);

		List<Node<String>> result = baseService.getRolePermissions(roleID);

		if (CollectionUtils.isEmpty(result)) {
			return renderFail(model, "未找到");
		} else {
			return renderSuccess(result, model);
		}
	}

	@ResponseBody
	@RequestMapping(value = "save.json", params = "oper=json")
	public Model add(HttpServletRequest request, Model model, @RequestBody JSONObject json) throws Exception {
		checkPermission(request, Permission.MANAGE.parts(_identity));
		logger.debug(json.toJSONString());

		SysRole record = new SysRole();
		record.setId(json.getInteger("id"));
		record.setName(json.getString("name"));
		record.setIdentity(json.getString("identity"));

		// 判断是添加还是修改
		if (StringUtils.equals("edit", json.getString("_oper"))) {
			baseService.update(record);
		} else {
			baseService.insert(record);
		}
		// 遍历提交的权限配置
		Map<String, String> permMap = new HashMap<>();

		JSONObject permJson = json.getJSONObject("permissions");
		if (permJson != null) {
			for (Entry<String, Object> entry : permJson.entrySet()) {
				permMap.put(entry.getKey(), String.valueOf(entry.getValue()));
			}
		}
		// 保存权限配置
		baseService.saveRolePermission(record.getId(), permMap);

		// 返回数据
		model.addAttribute("oper", json.get("_oper"));
		model.addAttribute("data", record);

		return renderSuccess(model);
	}
}
